﻿namespace Harness
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Diagnostics;

    internal class ThreadSynchronizer
    {
        private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        private TaskScheduler taskScheduler = null;

        public ThreadSynchronizer()
        {
            try
            {
                this.taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
            }
            catch
            {
            }
        }

        public void Sync(Action action)
        {
            this.Sync(delegate()
            { }, action);
        }

        public void Sync(Action action1, Action action2)
        {
            if (null == this.taskScheduler)
            {
                Debug.Print("taskScheduler = null");
                action1();
                action2();
            }
            else
            {
                Debug.Print("taskScheduler = {0}", taskScheduler.Id);
                Task.Factory.StartNew(() =>
                {
                    action1();
                }).ContinueWith(
                (ac) =>
                {
                    action2();
                },
                this.cancellationTokenSource.Token,
                TaskContinuationOptions.None,
                this.taskScheduler);
            }
        }
    }
}
